<?php

namespace app\hook;


use app\modules\Admin\models\cashbackgoodsModel;
use app\modules\Admin\models\pickgoodscardModel;
use app\modules\Admin\models\scoregoodsModel;
use app\service\member;
use Illuminate\Database\Capsule\Manager as DB;

class orderpayed
{
    public function after($params = [])
    {
        \Log::out('orderpayed after ' . json_encode($params), 'pay');
        // 订单支付成功
        $order = $params['order'];
        $notify = $params['notify'];

        // 更新订单支付状态，记录支付回调数据
        $order->status = \orderModel::STATUS_PAYED;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = json_encode($notify);
        $order->pay_type = $notify['pay_type'] ?? '';
        $order->save();
        $user = \memberModel::find($order->member_id);
        \orderactionModel::operAdd($order, null, $user, 'user', '用户支付成功');

        // 重新查询订单
        $order = \orderModel::with('item')->find($order['id']);

        // 积分商城能量商品扣除积分
        if ($order['type'] == 'score' && $order->score_fee > 0) {
            \memberModel::score(
                -$order->score_fee,
                $order->member_id,
                'orderpay',
                $order->id,
                "积分商品支付积分 订单编号{$order->order_sn}"
            );
        }

        // 如果是套餐订单，检查套餐中是否有提货卡
        $order_ext = json_decode($order->getRawOriginal('ext'), true);
        if (!empty($order_ext['combo'])) {
            $order_item = \orderitemModel::where('order_id', $order->id)->first();
            $goods_combo = json_decode($order_item->getRawOriginal('goods_combo'), true);
            if ($goods_combo['card']) {
                $cards = pickgoodscardModel::whereIn('id', array_column($goods_combo['card'], 'card_id'))->get();
                foreach ($goods_combo['card'] as $goods_combo_card_item) {
                    foreach ($cards as $card) {
                        if ($card->id == $goods_combo_card_item['card_id']) {
                            break;
                        }
                    }
                    $expire = null;
                    if (!empty($card['card_valid_day'])) {
                        $expire = date('Y-m-d H:i:s', strtotime("+ {$card['card_valid_day']} day"));
                    }
                    if (!empty($card['card_validtime_end'])) {
                        $expire = $card['card_validtime_end'];
                    }
                    for ($i = 0; $i < $goods_combo_card_item['card_num']; $i++) {
                        $card_sn = uniqid();
                        $card_sn = preg_replace('/[a-z]/', mt_rand(0, 9), $card_sn);
                        $card_sn = preg_replace('/[A-Z]/', mt_rand(0, 9), $card_sn);
                        $member_card[] = [
                            'card_sn' => $card_sn,
                            'card_id' => $card['id'],
                            'member_id' => $order->member_id,
                            'money' => $card['amount'],
                            'expire' => $expire,
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
            }
            if (!empty($member_card)) {
                DB::table('member_pickgoods_card')->insert($member_card);
            }
        }

        // 商品如果设置赠送积分增加用户积分
        $orderItemList = \orderitemModel::where('order_id', $order->id)->get();
        $orderItemSkuPriceIds = [];
        foreach ($orderItemList as $orderItemItem) {
            $orderItemSkuPriceIds[] = $orderItemItem->goods_sku_price_id;
        }
        $orderItemSkuPrice = \goodsskupriceModel::whereIn('id', $orderItemSkuPriceIds)->get();
        $give_score = 0;
        if (!empty($order_ext['combo'])) {
            $give_score = \goodsskupriceModel::where('id', $orderItemSkuPriceIds[0])->value('score');
        }else {
            foreach ($orderItemList as $orderItemItem) {
                foreach ($orderItemSkuPrice as $orderItemSkuPriceItem) {
                    if ($orderItemItem->goods_sku_price_id == $orderItemSkuPriceItem->id) {
                        $give_score += ($orderItemSkuPriceItem->score * $orderItemItem->goods_num);
                        break;
                    }
                }
            }
        }
        if ($give_score > 0) {
            $order_user_id = $order->customer_id ?: $order->member_id;
            \memberModel::score($give_score, $order_user_id, 'orderaward', $order->id, '购买商品赠送积分 订单编号' . $order->order_sn);
        }

        // 商品如果设置了代理分销商品,并开启了参与金豆分红,则发金豆
        foreach ($orderItemList as $item) {
            $agentGoods = \agentgoodsModel::query()->where('goods_id', $item->goods_id)->first();
            if($agentGoods && $agentGoods->status==1 && $agentGoods->gq_status==1){
                if ($agentGoods->gq_self_rules == 1) {
                    $gq_zigou_rules = $agentGoods->gq_zigou_rules ? json_decode($agentGoods->gq_zigou_rules, TRUE) : [];
                    $gq_tuijian_rules = $agentGoods->gq_tuijian_rules ? json_decode($agentGoods->gq_tuijian_rules, TRUE) : [];
                } else {
                    $jindouRules = \configModel::query()
                        ->where('type', 19)
                        ->whereIn('key', ['jindou_self_ratio', 'jindou_tuijian_ratio'])
                        ->pluck('value', 'key');
                    $gq_zigou_rules   = ["ratio"=>$jindouRules['jindou_self_ratio']];
                    $gq_tuijian_rules = ["ratio"=>$jindouRules['jindou_tuijian_ratio']];
                }
                $zigouCommission = $this->caculateGoodsCommission($gq_zigou_rules, $item->pay_price, $item->goods_num);
                $tuijianCommission = $this->caculateGoodsCommission($gq_tuijian_rules, $item->pay_price, $item->goods_num);

                $user = \memberModel::query()->find($item->member_id);
                if($user && $zigouCommission>0) {
                    \memberjindoulogModel::insert([
                        'member_id' => $user->id,
                        'event'     => 'orderpay',
                        'event_id'  => $item->order_id,
                        'before'    => $user->jindou,
                        'jindou'    => $zigouCommission,
                        'after'     => round(floatval($user->jindou) + floatval($zigouCommission), 2),
                        'remark'    => '会员自购下单获得金豆, 订单编号:' . $order->order_sn,
                        'created_at'=> timestamp(),
                    ]);
                    $user->increment('jindou', $zigouCommission);
                }
                if($user->parent_member_id>0 && $tuijianCommission > 0) {
                    $tuijianer = \memberModel::query()->find($user->parent_member_id);
                    \memberjindoulogModel::insert([
                        'member_id'  => $tuijianer->id,
                        'event'      => 'orderpay',
                        'event_id'   => $item->order_id,
                        'before'     => $tuijianer->jindou,
                        'jindou'     => $tuijianCommission,
                        'after'      => round(floatval($tuijianer->jindou) + floatval($tuijianCommission), 2),
                        'remark'     => '会员推荐下单获得金豆, 订单编号:' . $order->order_sn,
                        'created_at' => timestamp(),
                    ]);
                    $tuijianer->increment('jindou', $tuijianCommission);
                }
            }
        }


        // 商品如果设置了代理分销商品,并开启了参与权益收益,则发放权益
        foreach ($orderItemList as $item) {
            $agentGoods = \agentgoodsModel::query()->where('goods_id', $item->goods_id)->first();
            if($agentGoods && $agentGoods->status==1 && $agentGoods->qy_status==1){
                if ($agentGoods->qy_self_rules == 1) {
                    $qy_rules = $agentGoods->qy_rules ? json_decode($agentGoods->qy_rules, TRUE) : [];
                } else {
                    $quanyiRules = \configModel::query()
                        ->where('type', 19)
                        ->where('key',  'quanyi_ratio')
                        ->value('value');
                    $qy_rules   = ["ratio"=>$quanyiRules];
                }
                $commission = $this->caculateGoodsCommission($qy_rules, $item->pay_price, $item->goods_num);

                $user = \memberModel::query()->find($item->member_id);
                if($user && $commission>0) {
                    \memberquanyilogModel::insert([
                        'member_id' => $user->id,
                        'event'     => 'orderpay',
                        'event_id'  => $item->order_id,
                        'before'    => $user->quanyi,
                        'quanyi'    => $commission,
                        'after'     => round(floatval($user->quanyi) + floatval($commission), 2),
                        'remark'    => '会员下单获得消费补贴, 订单编号:' . $order->order_sn,
                        'created_at'=> timestamp(),
                    ]);
                    $user->increment('quanyi', $commission);
                }
            }

            // 若商品开启了参与返现收益, 则记录发放返现权益
            $cashGoods = cashbackgoodsModel::query()->where('goods_id', $item->goods_id)->first();
            if($cashGoods && $cashGoods->status==1){
                if ($cashGoods->back_money == 0 && $cashGoods->back_ratio == 0) {
                    $cashbackRules = \configModel::query()
                        ->where('type', 19)
                        ->where('key',  'cashback_ratio')
                        ->pluck('value', 'key')
                        ->toArray();
                    $fx_rules   = ["ratio"=>$cashbackRules['cashback_ratio'], "money"=>$cashbackRules['cashback_money']];
                } else {
                    $fx_rules = ["ratio"=>$cashGoods->back_ratio, "money"=>$cashGoods->back_money];
                }
                $commission = $this->caculateGoodsCommission($fx_rules, $item->pay_price, $item->goods_num);

                $item->increment('cashback', $commission);
            }
        }

        // 发放收益
        if (0) {
            $order_user_id = $order->customer_id ?: $order->member_id;
            $syuser = \memberModel::query()->find($order_user_id);
            $commission = $order->pay_fee * 1.00;
            \membershouyilogModel::insert([
                'member_id' => $syuser->id,
                'event'     => 'orderpay',
                'event_id'  => $order->id,
                'before'    => $syuser->shouyi,
                'shouyi'    => $commission,
                'after'     => round(floatval($syuser->shouyi) + floatval($commission), 2),
                'remark'    => '会员下单获得消费收益补贴, 订单编号:' . $order->order_sn,
                'created_at'=> timestamp(),
            ]);
            $syuser->increment('shouyi', $commission);
        }

        // 自动发货 && 判断是否有提现资格产品
        foreach ($orderItemList as $orderItemItem) {
            $withdrawGoodsTxt = \configModel::query()->where('type', 9)->where('key', 'withdraw_enbale_goods')->value('value');
            if(!empty($withdrawGoodsTxt) && $user->enable_withdraw == 0) {
                $withdrawGoods = explode(',', $withdrawGoodsTxt);
                if(in_array($orderItemItem->goods_id, $withdrawGoods)) {
                    $user->enable_withdraw = 1;
                    $user->save();
                }
            }

            switch($orderItemItem->dispatch_type){
                case 'selfetch':
                    if ($orderItemItem->goods_type == 'virtual') {
                        // 虚拟商品，核销券，自动发货
                        $this->selfetchSendItem($order, $orderItemItem, ['oper_type' => 'system']);
                    }
                    break;
                case 'autosend':
                    $this->autoSendItem($order, $orderItemItem, ['oper_type' => 'system']);
                    break;
            }
        }

        // 有门店相关的订单
        // $storeIds = [];
        // foreach ($items as $item) {
        //     if (in_array($item['dispatch_type'], ['store', 'selfetch']) && $item['store_id']) {
        //         $storeIds[] = $item['store_id'];
        //     }
        // }

        // $data = [];
        // if ($storeIds) {
        //     $data = [];
        //     // 存在门店，查询门店管理员
        //     $stores = \storeModel::with(['userStore.user'])->whereIn('id', $storeIds)->get();
        //     foreach ($stores as $key => $store) {
        //         $userStoreList = $store['user_store'] ?: [];
        //         unset($store['user_store']);
        //
        //         // 当前门店所有用户管理员
        //         $userList = [];
        //         foreach ($userStoreList as $user) {
        //             if ($user['user']) {
        //                 $userList[] = $user['user'];
        //             }
        //         }
        //
        //         // 有用户才能发送消息
        //         if ($userList) {
        //             $data[] = [
        //                 'store'    => $store,
        //                 'userList' => $userList
        //             ];
        //         }
        //     }
        // }

        // // 存在要通知的门店管理员
        // if ($data) {
        //     // 按门店为单位发送通知
        //     foreach ($data as $key => $sendData) {
        //         \addons\shopro\library\notify\Notify::send(
        //             $sendData['userList'],
        //             new \addons\shopro\notifications\store\Order([
        //                 'store' => $sendData['store'],
        //                 'order' => $order,
        //                 'event' => 'store_order_new'
        //             ])
        //         );
        //     }
        // }

        \Log::out("order {$order->id} pay success", 'pay');
    }

    private function caculateGoodsCommission($commissionRule, $amount = 0, $goodsNum = 1)
    {
        $commission = 0;
        if (isset($commissionRule['ratio']) && $commissionRule['ratio'] > 0) {
            $commission = round($amount * $commissionRule['ratio'] * 0.01, 2);
        }
        if (isset($commissionRule['money']) && $commissionRule['money'] > 0) {
            $commission = $commissionRule['money'] * $goodsNum;
        }
        return number_format($commission, 2, '.', '');
    }

    /**
     * selfetch 自提/到店 单商品发货
     */
    private function selfetchSendItem($order, $item, $data = [])
    {
        // 获取配送模板
        $dispatch = \dispatchModel::where('type', $item['dispatch_type'])->where('id', $item['dispatch_id'])->first();
        $type_ids = $dispatch['type_ids'] ?? '';
        $dispatch_selfetch_ids = explode(',', $type_ids);

        $dispatchSelfetch = \dispatchselfetchModel::whereIn('id', $dispatch_selfetch_ids)
            ->orderBy('id', 'asc')->first();

        $expiretime = null;       // 核销券过期时间
        if ($dispatchSelfetch) {
            if ($dispatchSelfetch['expire_type'] == 'day') {
                $expire_day = $dispatchSelfetch['expire_day'] > 0 ? $dispatchSelfetch['expire_day'] : 0;
                $expiretime = $expire_day ? (time() + ($expire_day * 86400)) : null;
            } else {
                $expiretime = $dispatchSelfetch['expire_time'] ?: null;
            }
        }

//        if ($item['goods_type'] == 'virtual') {
//            // 商品购买多件，自动生成多个码
//            for ($i = 0; $i < $item['goods_num']; $i++) {
//                $this->createVerify($order, $item, [
//                    'expiretime' => $expiretime
//                ]);
//            }
//        } else {
//            // 商品购买多件，只生成一个码
//            $this->createVerify($order, $item, [
//                'expiretime' => $expiretime
//            ]);
//        }

        $this->sendItem($order, $item, [
            "oper_type" => $data['oper_type'],
        ]);
    }



    /**
     * autosend 单商品自动发货
     */
    private function autoSendItem($order, $item, $data = [])
    {
        // 获取配送模板
        $dispatch = \dispatchModel::where('type', $item['dispatch_type'])->where('id', $item['dispatch_id'])->first();

        $dispatch_autosend_ids = explode(',', $dispatch->type_ids);
        $dispatchAutosend = \dispatchautosendModel::whereIn('id', $dispatch_autosend_ids)
            ->orderBy('id', 'asc')->first();

        $ext = [];
        if ($dispatchAutosend) {
            if (in_array($dispatchAutosend['type'], ['text', 'params'])) {
                $ext['autosend_type'] = $dispatchAutosend['type'];
                $autosend_content = $dispatchAutosend['content'];
                if ($dispatchAutosend['type'] == 'params') {
                    $autosend_content = \dispatchautosendModel::getParamsContent($autosend_content);
                }
                $ext['autosend_content'] = $autosend_content;
            } else if ($dispatchAutosend['type'] == 'card') {
                // 电子卡密，待补充
            }
        }

        $this->sendItem($order, $item, [
            'ext' => $ext,
            "oper_type" => $data['oper_type'],
        ]);
    }

    // 发货
    public function sendItem($order, $item, $data = [])
    {
        $item->express_name = $data['express_name'] ?? null;
        $item->express_code = $data['express_code'] ?? null;
        $item->express_no = $data['express_no'] ?? null;
        $ext = ['send_time' => time()];
        if (isset($data['ext']) && $data['ext']) {
            $ext = array_merge($ext, $data['ext']);
        }
        $item->ext = json_encode($item->setExt($item, $ext));
        $item->dispatch_status = \orderitemModel::DISPATCH_STATUS_SENDED;    // 已发货状态
        $item->save();

        $oper_type = $data['oper_type'] ?? 'system';
        $oper = $data['oper'] ?? 0;
        \orderactionModel::operAdd($order, $item, $oper, $oper_type, '系统自动发货订单');

        // 订单发货后
        $hookData = ['order' => $order, 'item' => $item];
        \Hook::emit('order_send_after', $hookData);
        return $item;
    }

}

